package top.cardone.validator.func;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.validator.GenericValidator;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author yao hai tao
 * @date 2016/9/19
 */
@Log4j2
public class RangeValidatorFunc extends RequiredValidatorFunc {
    public RangeValidatorFunc() {
        this.code = "range";
    }

    @Override
    public Map<String, Object> func(Map<String, Object> map, String key, Object rule, Object message) {
        if (log.isDebugEnabled()) {
            log.debug(this.code + ":" + key);
        }

        Double val = MapUtils.getDouble(map, key, new Double(0));

        if (Objects.isNull(val)) {
            return null;
        }

        if (rule == null) {
            return null;
        }

        if (!(rule instanceof List)) {
            return null;
        }

        List<Double> range = (List<Double>) rule;

        if (GenericValidator.isInRange(val, range.get(0), range.get(1))) {
            return null;
        }

        return this.getMessage(key, message, range.toArray());
    }
}